// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const {
	result_success,
	result_error
} = require('http-result-modle')
const crypto = require("crypto");
const db = uniCloud.database();

function getSoundUUID() {
	let dateVal = new Date();
	let uuid = "sound";
	let year = dateVal.getFullYear();
	let month = dateVal.getMonth() + 1;
	let day = dateVal.getDate();
	let hours = dateVal.getHours() + 8;
	let minutes = dateVal.getMinutes();
	let seconds = dateVal.getSeconds();

	let dateStr = "" + year + "" + (month > 10 ? month : ("0" + month)) + "" + (day > 10 ? day : ("0" + day)) +
		"" + (hours > 10 ? hours : ("0" + hours)) + "" + (minutes > 10 ? minutes : ("0" + minutes)) +
		"" + (seconds > 10 ? seconds : ("0" + seconds));

	uuid = uuid + dateStr;
	let sum = 20 - uuid.length;
	for (let i = 0; i < sum; i++) {
		uuid = uuid + Math.floor(Math.random() * 10);
	}
	return uuid;
}
/**
 * 获取云音响请求凭证
 */
function getAccessToken() {
	let appId = 'ZF142';
	let appSecret = '2021bsjZF142XCI';
	let timestamp = new Date().getTime();
	let requestId = getSoundUUID();
	let userCode = 'ZF142';

	let soundParams = [{
			key: 'appId',
			value: appId
		},
		{
			key: 'requestId',
			value: requestId
		},
		{
			key: 'timestamp',
			value: timestamp
		},
		{
			key: 'userCode',
			value: userCode
		}
	];

	let token = '';
	let encode = '';

	soundParams.forEach(function(param) {
		token += param.key + param.value;
		encode += param.key + '=' + param.value + '&';
	});

	let access_token = crypto.createHash('md5').update(token + appSecret, 'utf8').digest('hex').toUpperCase();
	let params = encode.substr(0, encode.length - 1);

	return {
		access_token: access_token,
		params: params
	};
}
module.exports = {
	_before: function() {

	},
	async play(params) {
		let tokenObj = getAccessToken()
		if (tokenObj && tokenObj.access_token && tokenObj.params) {
			let requestUrl = 'https://ioe.car900.com/v1/openApi/dev/controlDevice.json';
			let requestParam = '?' + tokenObj.params;

			requestParam += '&token=' + tokenObj.access_token;
			requestParam += '&devName=' + params.device_code;
			requestParam += '&bizType=' + '2';
			requestParam += '&content=' + params.content;

			requestUrl += requestParam;

			return await uniCloud.httpclient.request(requestUrl, {
				headers: {
					"content-type": "application/x-www-form-urlencoded",
				},
				method: 'GET',
				data: null,
				contentType: 'json', // 指定以application/json发送data内的数据
				dataType: 'json' // 指定返回值为json格式，自动进行parse
			});
		}
	}
}